<script setup lang="ts">
import { ref, watch, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';

// 路由与导航相关
const route = useRoute();
const router = useRouter();
const activeTab = ref(route.query.activeTab || 'all');

// 标签页配置数据
const tabs = ref([
  { name: 'all', title: '全部', path: '/hotStop/all' },
  { name: 'topics', title: '热榜', path: '/hotStop/topics' },
  { name: 'game1', title: '游戏1', path: '/hotStop/game1' },
  { name: 'game2', title: '游戏2', path: '/hotStop/game2' },
  { name: 'game3', title: '游戏3', path: '/hotStop/game3' },
]);

/**
 * 处理标签点击事件
 * @param tab - 点击的标签对象
 */
const handleTabClick = (tab) => {
  const tabInfo = tabs.value.find(t => t.name === tab.name);
  if (tabInfo?.path) {
    router.push({
      path: tabInfo.path,
      query: { ...route.query, activeTab: tab.name } // 保留原有查询参数
    });
  }
};

// 监听路由中activeTab变化，同步标签状态
watch(
    () => route.query.activeTab,
    (newVal) => {
      if (newVal) activeTab.value = newVal;
    },
    { immediate: true } // 初始化时立即执行
);

// 页面挂载时初始化activeTab参数
onMounted(() => {
  if (!route.query.activeTab) {
    router.replace({
      path: route.path,
      query: { ...route.query, activeTab: 'all' }
    });
  }
});
</script>

<template>
  <div class="hot-stop-container">
    <div class="main-container">
      <!-- 顶部导航栏 -->
      <header class="header">
        <h2>热点</h2>
        <div class="header-right">
          <van-icon name="search" />
          <van-icon name="envelopes-o" />
        </div>
      </header>

      <!-- 顶部标签页导航 -->
      <div class="tabs-container">
        <van-sticky>
          <van-tabs
              v-model:active="activeTab"
              @click-tab="handleTabClick"
              swipeable
          >
            <van-tab
                v-for="tab in tabs"
                :key="tab.name"
                :title="tab.title"
                :name="tab.name"
            />
          </van-tabs>
        </van-sticky>
      </div>

      <!-- 内容区域 -->
      <div class="content-container">
        <router-view/>
      </div>
    </div>
  </div>
</template>

<style scoped>
.hot-stop-container {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
  height: 56px;
  background-color: #fff;
  border-bottom: 1px solid #eee;
}

.header-right {
  display: flex;
  gap: 15px;
}

.tabs-container {
  margin-top: 10px;
  background-color: #fff;
}

.content-container {
  flex: 1;
  overflow-y: auto;
}
</style>